package com.amsp.oa.oademo.controller;

import com.amsp.oa.oademo.entity.AttendanceSummary;
import com.amsp.oa.oademo.service.AttendanceSummaryService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/attendance-summary")
@Api(tags = "考勤汇总接口")
public class AttendanceSummaryController {

    @Autowired
    private AttendanceSummaryService attendanceSummaryService;

    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping("/save")
    @ApiOperation("保存考勤汇总记录")
    public ResponseEntity<AttendanceSummary> save(@RequestBody AttendanceSummary attendanceSummary) {
        if (attendanceSummary.getId() != null) {
            attendanceSummaryService.updateById(attendanceSummary);
        } else {
            attendanceSummaryService.save(attendanceSummary);
        }
        return ResponseEntity.ok(attendanceSummary);
    }

    @PostMapping("/batch-save")
    @ApiOperation("批量保存考勤汇总记录")
    public ResponseEntity<List<AttendanceSummary>> batchSave(@RequestBody Map<String, Object> params) {
        try {
            List<AttendanceSummary> records = new ArrayList<>();
            List<Map<String, Object>> attendanceList = (List<Map<String, Object>>) params.get("attendanceList");

            for (Map<String, Object> item : attendanceList) {
                AttendanceSummary record = objectMapper.convertValue(item, AttendanceSummary.class);
                records.add(record);
            }

            attendanceSummaryService.saveOrUpdateBatch(records);
            return ResponseEntity.ok(records);
        } catch (Exception e) {
            throw new RuntimeException("批量保存失败：" + e.getMessage());
        }
    }

    @GetMapping("/list")
    @ApiOperation("获取考勤汇总记录列表")
    public ResponseEntity<IPage<AttendanceSummary>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        return ResponseEntity.ok(attendanceSummaryService.getPage(current, size));
    }

    @GetMapping("/{id}")
    @ApiOperation("获取考勤汇总记录详情")
    public ResponseEntity<AttendanceSummary> getById(@PathVariable Long id) {
        return ResponseEntity.ok(attendanceSummaryService.getById(id));
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除考勤汇总记录")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        attendanceSummaryService.removeById(id);
        return ResponseEntity.ok().build();
    }
}